package cn.jn.lhm.part05;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lhm 2753914576@qq.com
 * @time 2023/4/13 - 23:42
 **/
@Slf4j
public class Server {
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("Boss");

        Selector selector = Selector.open();

        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(8080));
        ssc.register(selector, SelectionKey.OP_ACCEPT, null);

        Worker[] workers = new Worker[Runtime.getRuntime().availableProcessors()];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Worker("work-" + i);
        }

        AtomicInteger count = new AtomicInteger(0);

        while (true) {
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                if (key.isAcceptable()) {
                    SocketChannel client = ssc.accept();
                    client.configureBlocking(false);
                    workers[count.getAndIncrement() % workers.length].register(client);
                    log.info("客户端成功注册--->" + client.getRemoteAddress());
                }
                iterator.remove();
            }
        }
    }

    @Slf4j
    private static class Worker implements Runnable {
        private final String name;

        private Selector selector;

        private final AtomicBoolean start = new AtomicBoolean(false);

        private final ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();

        public Worker(String name) {
            this.name = name;
        }

        @SuppressWarnings("all")
        public void register(SocketChannel sc) throws IOException {
            // 初始化数据并且启动线程
            if (start.compareAndSet(false, true)) {
                Thread thread = new Thread(this, name);
                selector = Selector.open();
                thread.start();
            }

            // 向Worker线程传递，注册当前 Channel 到 Selector上
            queue.add(() -> {
                try {
                    sc.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                } catch (ClosedChannelException e) {
                    throw new RuntimeException(e);
                }
            });

            // 唤醒 --令牌形式的环境
            selector.wakeup();
        }

        @SneakyThrows
        @Override
        public void run() {
            while (true) {
                selector.select();
                Runnable task = queue.poll();
                if (task != null) {
                    task.run();
                }
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    if (key.isReadable()) {
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer = (ByteBuffer) key.attachment();
                        channel.read(buffer);
                        buffer.flip();
                        log.info(Thread.currentThread().getName() + "--->" + channel.getRemoteAddress() + "--->" + Charset.defaultCharset().decode(buffer));
                        buffer.clear();
                    }
                }
            }
        }
    }
}
